<template>
  <div class="plan">
    <div class="user-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-planadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button v-btnpermission="'btn-planload'" type="primary"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="活动名称" prop="activityCode">
            <el-select v-model="params.activityCode" placeholder="--请选择--">
              <el-option
                v-for="item in activityDic"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="预案名称" prop="planName">
            <el-input v-model="params.planName" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="plan-list">
      <el-row>
        <el-col>
          <!-- 预案列表 -->
          <el-table :data="planList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column
              prop="activityName"
              label="活动名称"
            ></el-table-column>
            <el-table-column prop="name" label="预案名称"></el-table-column>
            <el-table-column prop="content" label="预案内容"></el-table-column>
            <el-table-column
              prop="modifyTime"
              label="最后修改时间"
            ></el-table-column>
            <el-table-column prop="isvalid" label="是否有效">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.isvalid"
                  disabled
                  :active-value="1"
                  :inactive-value="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-planupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-plandelete'"
                  @click="DeleteDialog(scope.row.id)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="params.total"
            v-model:page-size="params.pageSize"
            v-model:current-page="params.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <!-- 添加预案对话框 -->
      <el-dialog
        title="添加预案"
        v-model="addDialogVisible"
        @close="addDislogClosed"
      >
        <el-form
          :model="addPlanForm"
          :rules="palnsFormRulesMixin.addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="活动名称" prop="activityCode">
            <el-select
              v-model="addPlanForm.activityCode"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in activityDic"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预案名称" prop="name">
            <el-input v-model="addPlanForm.name"></el-input>
          </el-form-item>
          <el-form-item label="预案内容" prop="content">
            <el-input
              v-model="addPlanForm.content"
              type="textarea"
              :rows="5"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否有效" prop="isvalid">
            <el-checkbox
              v-model="addPlanForm.isvalid"
              :true-label="1"
              :false-label="0"
            ></el-checkbox>
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addFormSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog title="修改预案" v-model="editDialogVisible" width="30%">
        <el-form
          :model="editPlanForm"
          ref="editFormRef"
          :rules="palnsFormRulesMixin.editFormRules"
          label-width="100px"
        >
          <el-form-item label="活动名称" prop="activityCode">
            <el-select
              v-model="editPlanForm.activityCode"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in activityDic"
                :key="item.Code"
                :label="item.Name"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预案名称" prop="name">
            <el-input v-model="editPlanForm.name"></el-input>
          </el-form-item>
          <el-form-item label="预案内容" prop="content">
            <el-input
              v-model="editPlanForm.content"
              type="textarea"
              :rows="5"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否有效" prop="isvalid">
            <el-checkbox
              v-model="editPlanForm.isvalid"
              :true-label="1"
              :false-label="0"
            ></el-checkbox>
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editFormSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue';
import { getDicByTableName } from '@/network/dictionary.js';
// import qs from "qs";
import {
  getPlanList,
  addPlan,
  updatePlan,
  deletePlan,
  addPlanList,
} from '@/network/plan';
import { palnsFormRulesMixin } from '@/utils/mixin';
import { ElMessage, ElMessageBox } from 'element-plus';
import { importExcel } from '@/utils/excel';
// 搜索条件
let params = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  activityCode: '',
  planName: '',
});
//分页索引
const indexMethod = (index) => {
  return index + (params.page - 1) * params.pageSize + 1;
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addPlanList(res)
        .then(() => {
          ElMessage.success('导入成功');
          initDic();
          result();
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('导入失败！');
        });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
let activityDic = ref([]);
const onSubmit = async () => {
  let data = {
    page: params.page,
    pageSize: params.pageSize,
    activityCode: params.activityCode,
    planName: params.planName,
  };
  await getPlanList(data).then((res) => {
    params.total = res.total;
    planList.value = res.data;
  });
};
//时间格式化
const rTime = (time) => {
  var date = new Date(time);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = date.getDate();
  d = d < 10 ? '0' + d : d;
  var h = date.getHours();
  h = h < 10 ? '0' + h : h;
  var minute = date.getMinutes();
  minute = minute < 10 ? '0' + minute : minute;
  var s = date.getSeconds();
  s = s < 10 ? '0' + s : s;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s;
};
const onReset = () => {
  params.activityCode = '';
  params.planName = '';
  params.page = 1;
  result();
};
// 添加角色对话框的显示和隐藏
let addDialogVisible = ref(false);
// 编辑对话框的显示和隐藏
let editDialogVisible = ref(false);
const addFormRef = ref(null);
const editFormRef = ref(null);
let addPlanForm = ref({
  name: '',
  content: '',
  modifyTime: rTime(Date()),
  isvalid: 1,
  path: '',
  activityCode: 1,
});

let editPlanForm = ref({
  id: 0,
  name: '',
  content: '',
  modifyTime: rTime(Date()),
  isvalid: 1,
  path: '',
  activityCode: 1,
});
let planList = ref([]);
const result = async () => {
  await getPlanList(params).then((res) => {
    planList.value = res.data;
    params.total = res.total;
  });
};
const initDic = async () => {
  await getDicByTableName({ tableName: 'tactivity' }).then((res) => {
    activityDic.value = res;
  });
};
onBeforeMount(() => {
  result();
  initDic();
});
const handleCurrentChange = () => {
  result();
};
// 添加预案
const addFormSubmit = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      await addPlan(addPlanForm.value)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '增加预案成功！',
          });
          result();
          addDialogVisible.value = false;
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '增加预案失败！',
          });
        });
    } else {
      ElMessage.error('请填写必要的必填项！');
      return false;
    }
  });
};
// 修改
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  editPlanForm.value = JSON.parse(JSON.stringify(row));
};
const editFormSubmit = () => {
  const formRef = editFormRef.value;
  editDialogVisible.value = false;
  editPlanForm.value.modifyTime = rTime(Date.now());
  formRef.validate(async (valid) => {
    if (valid) {
      await updatePlan(editPlanForm.value)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '修改预案成功！',
          });
          result();
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('修改失败！');
        });
    } else {
      ElMessage.error('请填写必要的必填项！');
    }
  });
};
// 删除
const DeleteDialog = (id) => {
  ElMessageBox.confirm('确定删除该预案吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(async () => {
    await deletePlan({ code: id })
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除预案成功！',
        });
        result();
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error('删除失败！');
      });
  });
};
const addDislogClosed = () => {
  // addPlanForm.value = {};
  addFormRef.value.clearValidate();
  addFormRef.value.resetFields();
  addDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.plan {
  margin: 14px 15px 14px;
  .user-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .plan-list {
    margin-top: 14px;
  }
}
</style>
